package com.lagou.guavademo.guava;

import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;

import java.util.Iterator;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;

public class Demo1 {

    /**
     * 初始化缓存
     */
    public static void initCache(LoadingCache<String, Object> cache) throws ExecutionException {
        for (int i = 1; i <= 3; i++) {
            // 连接数据源，如果缓存没有则读取数据源
            cache.get(String.valueOf(i));
        }
    }

    /**
     * 显示缓存内容
     * @param cache
     */
    public static void display(LoadingCache<String, Object> cache) {
        Iterator it = cache.asMap().entrySet().iterator();
        while (it.hasNext()) {
            System.out.println(it.next().toString());
        }
    }

    /**
     * 读取缓存数据，如果没有则回调源数据并回填
     * @param key
     * @param cache
     */
    public static void get(String key, LoadingCache<String, Object> cache) throws ExecutionException {
        cache.get(key, new Callable<Object>() {

            @Override // 回调方法用于读源并写入缓存
            public Object call() throws Exception {
                // 读源
                Object value = Constants.hm.get(key);
                // 回填缓存
                cache.put(key, value);
                return value;
            }
        });
    }

    public static void main(String[] args) throws ExecutionException {
        LoadingCache<String, Object> cache = CacheBuilder.newBuilder().build(new CacheLoader<String, Object>() {
            @Override
            public Object load(String key) throws Exception {
                return Constants.hm.get(key);
            }
        });

        // 初始化缓存
        initCache(cache);
        System.out.println(cache.size());

        // 显示缓存数据
        display(cache);

        get("4", cache);
        System.out.println("========================");
        display(cache);
    }
}
